package com.aispeech.asr.webase.actuator;

import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import com.aispeech.asr.comm.utils.HttpUtils;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@WebEndpoint(id = "opsmind")
public class Opsmind {
	
	@Autowired
    WebClient webClient;
	
	@Value("${apis.dopc.opsmind-port:-1}")
	private Integer[] opsmindPort;
	
	private static String opsmindUrl = "http://127.0.0.1:%d/opsmind";
	
	
    //@GetMapping(value = {"/opsmind"})
    @ReadOperation(produces = MediaType.TEXT_PLAIN_VALUE)
    public String opsmind() throws IOException {
    	//log.warn("[Opsmind] metrics start.");
        Set<String> stringSet = new HashSet<>();
//        List<String> names = null; // request.getQueryParams().getOrDefault("name", null);
//        if (names != null) {
//            stringSet.addAll(names);
//        }
        CollectorRegistry registry = CollectorRegistry.defaultRegistry;
        final BufferWriter writer = new BufferWriter();
        TextFormat.write004(writer, registry.filteredMetricFamilySamples(stringSet));
        
        if(opsmindPort != null && opsmindPort.length > 0) {
        	for(int port : opsmindPort) {
        		//log.warn("[Opsmind] ops metrics port:{}.",port);
        		if(port > 0) {
            		String requestUrl = String.format(opsmindUrl, port);
            		
            		try {
            			String result = HttpUtils.get(requestUrl);
                		//log.warn("[Opsmind] ops metrics result:{}.",result);
                		writer.write(result);
            		}catch (Exception e) {
    					log.warn("[Opsmind] get ops metrics result from: {}. caused by: {}", requestUrl, e.getMessage());
    				}
        		}
        	}
        }

        return writer.buffer.toString();
    }

    private static class BufferWriter extends Writer {
        private final StringBuilder buffer = new StringBuilder();

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            buffer.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {

        }

        @Override
        public void close() throws IOException {

        }
    }
}
